<?php


namespace app\admin\controller;


use app\constant\ActivesConst;
use app\constant\OrderConst;
use app\helper\OrderHelper;
use app\helper\WxHelper;
use app\model\AdminActives;
use app\model\AdminOrder;
use app\model\AdminStores;
use app\util\ReturnCode;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use think\exception\DbException;

class Order extends Base

{
    public function del()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $where = [];
        $where = $this->addTid($where);
        $where['del'] = 0;
        $where['id'] = $id;
        $model = AdminOrder::get($where);
        if (!$model) {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '此订单不存在');
        }
        if ($model->trade_status !== OrderConst::ORDER_STATUS_CLOSE) {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '只有已关闭的订单可删除');
        }
        $model->setAttr('del', 1);
        $done = $model->save();
        if ($done) {
            return $this->buildSuccess([]);
        }
        return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败');
    }

    public function getDetail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $where = [];
        $where = $this->addTid($where);
        $where['del'] = 0;
        $where['id'] = $id;
        $model = AdminOrder::get($where);
        if (!$model) {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '此订单不存在');
        }
        $items = $model->item;
        $data = $model->getData();

        foreach ($items as $item) {
            $storeData = AdminStores::get($item['sid'])->getData();
            $item['store_name'] = $storeData['name'];
            $item['store_id'] = $storeData['id'];
        }
        $data['item'] = $items;

        return $this->buildSuccess($data);
    }

    public function getList()
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $search_type = $this->request->get('search_type', '', 'intval');
        $type = $this->request->get('type', '', 'intval');
        $sort = $this->request->get('sort', 'desc');
        $goods_id = $this->request->get('goods_id');
        $goods_type = $this->request->get('goods_type');
        $keywords = $this->request->get('keywords', '');
        $where = ['del' => 0];
        if (isset($goods_id)) {
            $where['goods_id'] = $goods_id;
        }
        $where = $this->addTid($where);
        $obj = new AdminOrder();
        if ($search_type) {
            switch ($search_type) {
                case 1://买家姓名
                    $obj = $obj->whereLike('user_name', "%{$keywords}%");
                    break;
                case 2://手机号
                    $obj = $obj->whereLike('user_phone', "%{$keywords}%");
                    break;
                case 3://订单号
                    $obj = $obj->where('id', $keywords);
                    break;
            }
        }
        //订单类型 0 全部 1未付款 2待使用 3待收货 4待评价5已过期6已退款
        if (isset($goods_type)&&$goods_type==ActivesConst::ACTIVE_TYPE_VIP){
            $where['goods_type'] = $goods_type;
        }else{
            $obj =$obj->whereNotIn('goods_type',ActivesConst::ACTIVE_TYPE_VIP);
        }
        switch ($type) {
            case 1:
                $where['pay_status'] = OrderConst::PAY_STATUS_UN_PAY_ONLINE;
                $where['trade_status'] = OrderConst::ORDER_STATUS_NORMAL;
                break;
            case 2:
                $where['pay_status'] = OrderConst::PAY_STATUS_PAID_ONLINE;
                $where['trade_status'] = OrderConst::ORDER_STATUS_NORMAL;
                break;
            case 3:
                $where['pay_status'] = [OrderConst::PAY_STATUS_PAID_ONLINE, OrderConst::PAY_STATUS_UN_PAY_OFFLINE];//这个一般是发实物货的，所以有线上支付或线下货到付款支付两种
                $where['trade_status'] = OrderConst::ORDER_STATUS_NORMAL;
                $where['type'] = OrderConst::ORDER_TYPE_EXPRESS;
                break;
            case 4:
                $where['trade_status'] = OrderConst::ORDER_STATUS_USED;
                break;
            case 5:
                $where['trade_status'] = OrderConst::ORDER_STATUS_EXPIRE;
                break;
            case 6:
                $where['pay_status'] = OrderConst::PAY_STATUS_REFUNDED;
                break;
        }
        try {
            $listObj = $obj->where($where)->order('create_time ' . $sort)->paginate($limit, false, ['page' => $start])->each(function ($value, $key) use ($goods_type) {
                $value->item;
                $storeData = AdminStores::get($value->item[0]['sid'], null, true)->getData();
                $value->store_name = $storeData['name'];
                $value->store_id = $storeData['id'];

            })->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED, '获取失败');

    }

    /**
     * 发起退款
     * 退款操作流程：
     * 1、发起退款，区分退款类型，如果是退款到余额，则直接增加余额，如果是退到微信，则需要根据支付订单号发起退款
     *    其中退款到微信需要读取退款比例配置中的数据
     * 2、标记为退款中状态
     * 3、退款完成标记订单为已退款
     * 4、修改主订单及子订单交易状态为关闭
     * 5、涉及分销的要标识分销为关闭状态
     * 6、涉及佣金的要标识为关闭
     *
     */
    public function refund()
    {
        $helper = new OrderHelper();
        $result = $helper->applyRefund($this->request,$this->getUserTid());
        if($result['code']==ReturnCode::SUCCESS){
            return $this->buildSuccess(null);
        }else{
            return $this->buildFailed($result['code'],$result['msg']);
        }
    }

}